﻿using System;

public class BindableProperty<T>
{
    public bool IsForce { get; set; }

    private Action<T, T> OnValueChange;

    private T curValue;

    private T oldValue;

    public T Property
    {
        get { return curValue; }
        set
        {
            if (IsForce || !Equals(Property, value))
            {
                oldValue = curValue;
                curValue = value;
                Publish();
            }
        }
    }

    public bool IsSubscribe(Action<T, T> valueChange)
    {
        Delegate[] delegates = OnValueChange.GetInvocationList();
        return Array.IndexOf(delegates, valueChange) > 0;
    }

    public void Subscribe(Action<T, T> valueChange)
    {
        OnValueChange += valueChange;
    }

    public void Unsubscribe(Action<T, T> valueChange)
    {
        OnValueChange -= valueChange;
    }

    public void Publish()
    {
        if (OnValueChange != null)
        {
            OnValueChange(oldValue, curValue);
        }
    }

    public void Freed()
    {
        OnValueChange = null;
    }
}